<?php
namespace app\admin\controller;
use think\Controller;

class News extends Controller
{
    /**
     * 新闻列表
     */
    public function newslist(){
        $data = Db('news')->order('id','desc')->paginate(10);
        $page = $data->render();
        $this->assign('page',$page);
        $this->assign('data',$data);
        return view('news/index');
    }


    /**
     * 添加新闻
     */
    public function add(){
        if(request()->isPost()){
            $content = input('content');
            // dump($content);exit;
            $post = input('post.');
            // 获取表单上传文件
            $files[0] = request()->file('image1');
            $files[1] = request()->file('image2');
            //判断新闻图是否上传
            if(!empty($files[0])){
                //判断banner图是否上传
                if(!empty($files[1])){
                    $arr = array();
                    foreach($files as $file){
                        // 移动到框架应用根目录/public/uploads/ 目录下
                        $info = $file->validate(['size'=>3145728,'ext'=>'jpg,png,gif'])->rule('uniqid')->move(ROOT_PATH . 'public' . DS . 'uploads');
                        $error = $file->getError();
                        //验证文件后缀后大小
                        if(!empty($error)){
                            dump($error);exit;
                        }
                        if($info){
                            // 成功上传后 获取上传信息
                            //把上传返回的文件名赋值到空数组中,方便调用
                            $arr[] =  $info->getFilename();
                        }else{
                            // 上传失败获取错误信息
                            echo $file->getError();
                        }
                    }
                    $post['news_img'] = $arr[0];
                    $post['news_banner'] = $arr[1];
                }else{
                    $info = $files[0]->validate(['size'=>3145728,'ext'=>'jpg,png,gif'])->rule('uniqid')->move(ROOT_PATH . 'public' . DS . 'uploads');
                    $error = $file[0]->getError();
                    //验证文件后缀后大小
                    if(!empty($error)){
                        dump($error);exit;
                    }
                    if($info){
                        // 成功上传后 获取上传信息
                        // 输出 jpg
                        $info->getExtension();
                        // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                        $info->getSaveName();
                        // 输出 42a79759f284b767dfcb2a0197904287.jpg
                        $post['news_img'] = $info->getFilename();
                        $post['news_banner'] = '';
                        $post['banner_statuid'] = 0;
                    }else{
                        // 上传失败获取错误信息
                        $file->getError();
                    }
                }
            }else{
                $this->error('新闻图片必须上传');
            }
            $num = Db('news')->insert(['news_title'=>$post['news_title'],'news_content'=>$content,'author'=>$post['author'],'news_img'=>$post['news_img'],'news_banner'=>$post['news_banner'],'banner_statuid'=>$post['banner_statuid'],'news_brief'=>$post['news_brief'],'headlines'=>$post['headlines'],'news_statuid'=>$post['news_statuid'],'news_time'=>date('y-m-d h:i:s')]);
            if($num>0){
                $this->success('添加成功');
            }else{
                $this->error('添加失败');
            }
        }
        return view('add');
    }


    /**
     * 新闻编辑
     */
    public function edit($id){
        if(request()->isPost()){
            $content = input('content');
            $post = input('post.');
            $id = $post['id'];
            $num = Db('news')->where('id',$id)->update(['news_title'=>$post['news_title'],'news_content'=>$content,'author'=>$post['author'],'news_brief'=>$post['news_brief'],'banner_statuid'=>$post['banner_statuid'],'news_statuid'=>$post['news_statuid'],'headlines'=>$post['headlines'],'news_time'=>date('y-m-d h:i:s')]);
            if($num>0){
                $this->success('修改成功');
            }else{
                $this->error('修改失败');
            }
        }
        $data= Db('news')->where('id',$id)->find();
        $this->assign('data',$data);
        return view('news/edit');
    }


    /**
     * 跳转更换新闻图片
     */
    public function news_img($id){
        if(request()->isPost()){
            $post = input('post.');
            // 获取表单上传文件
            $file = request()->file('image');

                if(!empty($file)){
                    // 移动到框架应用根目录/public/uploads/ 目录下
                    $info = $file->validate(['size'=>3145728,'ext'=>'jpg,png,gif'])->rule('uniqid')->move(ROOT_PATH . 'public' . DS . 'uploads');
                    $error = $file->getError();
                    //验证文件后缀后大小
                    if(!empty($error)){
                        dump($error);exit;
                    }
                    if($info){
                        // 成功上传后 获取上传信息
                        // 输出 jpg
                        $info->getExtension();
                        // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                        $info->getSaveName();
                        // 输出 42a79759f284b767dfcb2a0197904287.jpg
                        $post['news_img'] = $info->getFilename();

                    }else{
                        // 上传失败获取错误信息
                        $file->getError();
                    }
                }else{
                    $post['news_img'] = '';
                }

            $num = Db('news')->where('id',$post['id'])->setField(['news_img'=>$post['news_img']]);
            if($num>0){
                $this->success('更新成功');
            }else{
                $this->error('更新失败');
            }
        }
        $data = Db('news')->where('id',$id)->find();
        $this->assign('data',$data);
        return view('news_img');
    }

    /**
     * 跳转更换新闻banner图片
     */
    public function news_banner($id){
        if(request()->isPost()){
            $post = input('post.');
            // 获取表单上传文件
            $file = request()->file('image');

                if(!empty($file)){
                    // 移动到框架应用根目录/public/uploads/ 目录下
                    $info = $file->validate(['size'=>3145728,'ext'=>'jpg,png,gif'])->rule('uniqid')->move(ROOT_PATH . 'public' . DS . 'uploads');
                    $error = $file->getError();
                    //验证文件后缀后大小
                    if(!empty($error)){
                        dump($error);exit;
                    }
                    if($info){
                        // 成功上传后 获取上传信息
                        // 输出 jpg
                        $info->getExtension();
                        // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                        $info->getSaveName();
                        // 输出 42a79759f284b767dfcb2a0197904287.jpg
                        $post['news_banner'] = $info->getFilename();
                    }else{
                        // 上传失败获取错误信息
                        return $file->getError();
                    }
                }else{
                    $post['news_banner'] = '';
                }


            $num = Db('news')->where('id',$post['id'])->setField(['news_banner'=>$post['news_banner']]);
            if($num>0){
                $this->success('更新成功');
            }else{
                $this->error('更新失败');
            }
        }
        $data = Db('news')->where('id',$id)->find();
        $this->assign('data',$data);
        return view('news_banner');
    }



    /**
     * 删除
     */
    public function delete(){
        if(request()->isPost()){
            $post = input('post.');
            $id = $post['uid'];
            if(!empty($id)){
                $num = Db('news')->where('id',$id)->delete();
                if($num>0){
                    //删除成功
                    return 1;
                }else{
                    //删除失败
                    return 2;
                }
            }else{
                //id不存在
                return 3;
            }
        }else{
            //请求格式不对
            return 4;
        }
    }

    /**
     * 详情
     */
    public function details(){
        if(request()->isPost()){
            $post = input('post.');
            $id = $post['id'];
            if(!empty($id)){
                $news_content = Db('news')->where('id',$id)->value('news_content');
                return $news_content;
            }else{
                //新闻不存在
                return 2;
            }
        }else{
            //请求格式不对
            return 3;
        }
    }


    /**
     * 修改banner状态
     */
    public function changebanner(){
        if(request()->isPost()){
            $post = input('post.');
            $id = $post['id'];
            $statuid = $post['banner_statuid'];

            if($statuid == 1){
                $statuid = 0;
                $num = Db('news')->where('id',$id)->update(['banner_statuid'=>$statuid]);
                if($num>0){
                    return json(['statuid'=>$statuid,'msg'=>'修改成功']);
                }else{
                    $statuid = 1;
                    return json(['statuid'=>$statuid,'msg'=>'修改失败']);
                }
            }else{
                $statuid = 1;
                $num = Db('news')->where('id',$id)->update(['banner_statuid'=>$statuid]);
                if($num>0){
                    return json(['statuid'=>$statuid,'msg'=>'修改成功']);
                }else{
                    $statuid = 0;
                    return json(['statuid'=>$statuid,'msg'=>'修改失败']);
                }
            }
        }
    }



    /**
     * 修改新闻状态
     */
    public function changenews(){
        if(request()->isPost()){
            $post = input('post.');
            $id = $post['id'];
            $statuid = $post['news_statuid'];

            if($statuid == 1){
                $statuid = 0;
                $num = Db('news')->where('id',$id)->update(['news_statuid'=>$statuid]);
                if($num>0){
                    return json(['statuid'=>$statuid,'msg'=>'修改成功']);
                }else{
                    $statuid = 1;
                    return json(['statuid'=>$statuid,'msg'=>'修改失败']);
                }
            }else{
                $statuid = 1;
                $num = Db('news')->where('id',$id)->update(['news_statuid'=>$statuid]);
                if($num>0){
                    return json(['statuid'=>$statuid,'msg'=>'修改成功']);
                }else{
                    $statuid = 0;
                    return json(['statuid'=>$statuid,'msg'=>'修改失败']);
                }
            }
        }
    }


    /**
     * 导出
     */
    public function export(){
        $xlsData = Db('news')->select();
        Vendor('PHPExcel.PHPExcel');
        Vendor('PHPExcel.PHPExcel.Worksheet.Drawing');
        Vendor('PHPExcel.PHPExcel.Writer.Excel2007');
        $objExcel = new \PHPExcel();
        //set document Property
        $objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');

        $objActSheet = $objExcel->getActiveSheet();
        $key = ord("A");
        $letter =explode(',',"A,B,C,D,E,F");
        $arrHeader = array('新闻标题','新闻内容','发布时间','banner状态','新闻状态','作者');
        //填充表头信息
        $lenth =  count($arrHeader);
        for($i = 0;$i < $lenth;$i++) {
            $objActSheet->setCellValue("$letter[$i]1","$arrHeader[$i]");
        };
        //填充表格信息
        foreach($xlsData as $k=>$v){
            $k +=2;
            $objActSheet->setCellValue('A'.$k,$v['news_title']);
            $objActSheet->setCellValue('B'.$k, $v['news_content']);
            // // 图片生成
            // $objDrawing[$k] = new \PHPExcel_Worksheet_Drawing();
            // $objDrawing[$k]->setPath('public/static/admin/images/profile_small.jpg');
            // // 设置宽度高度
            // $objDrawing[$k]->setHeight(40);//照片高度
            // $objDrawing[$k]->setWidth(40); //照片宽度
            // /*设置图片要插入的单元格*/
            // $objDrawing[$k]->setCoordinates('C'.$k);
            // // 图片偏移距离
            // $objDrawing[$k]->setOffsetX(30);
            // $objDrawing[$k]->setOffsetY(12);
            // $objDrawing[$k]->setWorksheet($objPHPExcel->getActiveSheet());
            // 表格内容
            $objActSheet->setCellValue('C'.$k, $v['news_time']);
            $objActSheet->setCellValue('D'.$k, $v['banner_statuid']==1?'显示':'隐藏');
            $objActSheet->setCellValue('E'.$k, $v['news_statuid'] == 1?'正常':'失效');
            $objActSheet->setCellValue('F'.$k, $v['author']);


            // 表格高度
            $objActSheet->getRowDimension($k)->setRowHeight(20);
        }

        $width = array(20,20,15,10,10,30,10,15,40);
        //设置表格的宽度
        $objActSheet->getColumnDimension('A')->setWidth($width[5]);
        $objActSheet->getColumnDimension('B')->setWidth($width[8]);
        $objActSheet->getColumnDimension('C')->setWidth($width[0]);
        $objActSheet->getColumnDimension('D')->setWidth($width[5]);
        $objActSheet->getColumnDimension('E')->setWidth($width[5]);


        $outfile = "新闻表.xls";
        ob_end_clean();
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="'.$outfile.'"');
        header("Content-Transfer-Encoding: binary");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");
        $objWriter->save('php://output');
    }


    /*
     *上传
     */
    public function upload(){
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');
        // $file = Request::instance()->file('file');
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->rule('uniqid')->move(ROOT_PATH . 'public' . DS . 'uploads');
        if($info){
                $name_path =str_replace('\\',"/",$info->getFilename());
                //成功上传后 获取上传信息
                $result["code"] = '0';
                $result["msg"] = "上传成功";
                $result['data']["src"] =  '/vdma/public' . DS . 'uploads/'.$name_path;
            }else{
                  // 上传失败获取错误信息
                $result["code"] = "2";
                $result["msg"] = "上传出错";
                $result['data']["src"] ='';
            }
        return json_encode($result);
    }


    /**
     * 修改头条状态
     */
    public function headlines(){
        $param = input('param.');
        if($param['id']){
            if($param['headlines'] == 1){
                $headlines = 0;
                $num = Db('news')->where('id',$param['id'])->update(['headlines'=>$headlines]);
                if($num>0){
                    return ['code'=>1,'msg'=>'成功','headlines'=>0];
                }else{
                    return ['code'=>400,'msg'=>'失败'];
                }
            }else{
                $headlines = 1;
                $num = Db('news')->where('id',$param['id'])->update(['headlines'=>$headlines]);
                if($num>0){
                    return ['code'=>1,'msg'=>'成功','headlines'=>1];
                }else{
                    return ['code'=>400,'msg'=>'失败'];
                }
            }

        }
    }

















}